package com.example.calculator

import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import org.mariuszgromada.math.mxparser.Expression
import java.util.*

class MainActivity : AppCompatActivity() {
    private lateinit var buttons: ArrayList<Button>//按键集合
    private lateinit var screen: TextView
    private lateinit var resultScreen: TextView
    private var themeId = 0
    private var buttonsId = intArrayOf(//按键id集合
        R.id.AC,
        R.id.backspace,
        R.id.mode,
        R.id.expect,
        R.id.seven,
        R.id.eight,
        R.id.nine,
        R.id.multiply,
        R.id.four,
        R.id.five,
        R.id.six,
        R.id.subtract,
        R.id.one,
        R.id.two,
        R.id.three,
        R.id.add,
        R.id.change,
        R.id.zero,
        R.id.point,
        R.id.equal
    )
    private lateinit var calText: StringBuilder
    private lateinit var screenText: StringBuilder
    private lateinit var inputHistory: Stack<String>
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        appInit()
    }

    private fun appInit() {
        buttons = ArrayList<Button>()//按键集合
        screen = findViewById(R.id.screen)
        resultScreen = findViewById(R.id.result_screen)
        inputHistory = Stack()
        calText = StringBuilder()
        screenText = StringBuilder()
        buttonInit()
        for (i in buttons) {
            buttonListener(i)
        }
    }

    private fun buttonInit() {
        for (i in buttonsId) {
            buttons.add(findViewById(i))
        }
    }

    private fun myCalculate(addChar: String) {
        val nonNumeric = listOf("+", "*", "-", "/", ".", "÷")
        //输入情况
        when (addChar) {
            "c" -> {//清空
                calText.setLength(0)
                inputHistory.clear()
                screenText.setLength(0)
            }
            "b" -> {//退格
                if (inputHistory.empty()) return
                val tem = inputHistory.pop()
                val tem2 = calText.findLastAnyOf(listOf(tem))?.first
                if (tem.length > 1) calText.deleteRange(tem2!!, calText.lastIndex + 1)
                else calText.deleteCharAt(tem2!!)
                screenText.deleteAt(screenText.lastIndex)
            }
            "%" -> {
                val tem = nonNumeric.toMutableList()
                tem.add("%")
                if (!("0" <= addChar && addChar <= "9") && inputHistory.isNotEmpty() &&
                    tem.contains(screenText.takeLast(1))
                ) return
                if (inputHistory.isEmpty() && tem.contains(addChar)) return//初始时不可输入数字以外的
                screenText.append("%")
                calText.append("*0.01")
                inputHistory.push("*0.01")
            }
            "=" -> {
                val tem = Expression(calText.toString()).calculate().toString()
                myCalculate("c")
                screen.text = tem
                return
            }
            else -> {
                if (inputHistory.isEmpty() && nonNumeric.contains(addChar)) return//初始时不可输入数字以外的
                if (!("0" <= addChar && addChar <= "9")) {//输入非数字时
                    //若上次输入为非数字不响应
                    if (inputHistory.isNotEmpty() &&
                        nonNumeric.contains(screenText.takeLast(1))
                    ) return
                    if (addChar == ".") {//禁止一个数出现多小数点
                        val tem2 = StringBuilder(calText)
                        for (i in tem2.append(addChar).split('+', '-', '*', '/')) {
                            if (i.split('.').count() > 2) return
                        }
                    }
                } else {//输入数字时
                    val tem3 = StringBuilder(calText)
                    if (screenText.isNotEmpty()) {//禁止一个数以零开头
                        val i = tem3.append(addChar).split('+', '-', '*', '/').lastOrNull()
                        if (i?.getOrNull(0) == '0' && i?.getOrNull(1) != '.' && i?.getOrNull(1) != null) return
                    }
                    if (screenText.takeLast(1) == "%") {//百分号后输入数字不响应
                        return
                    }
                }

                calText.append(addChar)
                inputHistory.push(addChar)
                if (addChar == "/") {
                    screenText.append("÷")
                } else
                    screenText.append(addChar)
            }
        }
        screen.text = screenText
        val calRs = Expression(calText.toString()).calculate().toString()
        if (calRs != "NaN" && screenText.isNotEmpty()) {//不计算无法计算的表达式
            resultScreen.text = calRs
        } else if (screenText.isEmpty()) {
            resultScreen.text = ""
        }
    }

    /***
     *修改所有button属性
     */
    private fun changeTheme() {
        if (themeId == 0) {
            themeId = 1
            setContentView(R.layout.activity_second)
            appInit()
        } else {
            themeId = 0
            setContentView(R.layout.activity_main)
            appInit()
        }
    }


    private fun buttonListener(button: Button) {
        button.setOnClickListener {
            when (it?.id) {
                (R.id.AC) -> {
                    myCalculate("c")
                }
                (R.id.backspace) -> {
                    myCalculate("b")
                }
                (R.id.mode) -> {
                }
                (R.id.expect)
                -> {
                    myCalculate("/")
                }
                (R.id.seven)
                -> {
                    myCalculate("7")
                }
                //myCalculate("%")
                (R.id.eight)
                -> {
                    myCalculate("8")
                }
                (R.id.nine)
                -> {
                    myCalculate("9")
                }
                (R.id.multiply)
                -> {
                    myCalculate("*")
                }
                (R.id.four)
                -> {
                    myCalculate("4")
                }
                (R.id.five)
                -> {
                    myCalculate("5")
                }
                (R.id.six)
                -> {
                    myCalculate("6")
                }
                (R.id.subtract)
                -> {
                    myCalculate("-")
                }
                (R.id.one)
                -> {
                    myCalculate("1")
                }
                (R.id.two)
                -> {
                    myCalculate("2")
                }
                (R.id.three)
                -> {
                    myCalculate("3")
                }
                (R.id.add)
                -> {
                    myCalculate("+")
                }
                (R.id.change)
                -> {
                    changeTheme()
                }
                (R.id.zero)
                -> {
                    myCalculate("0")
                }
                (R.id.point)
                -> {
                    myCalculate(".")
                }
                (R.id.equal)
                -> {
                    myCalculate("=")
                }
            }
        }
    }
}